package com.jjiang.bbmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jjiang.bbmall.product.service.CategoryBrandRelationService;
import com.jjiang.bbmall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjiang.common.utils.PageUtils;
import com.jjiang.common.utils.Query;

import com.jjiang.bbmall.product.dao.CategoryDao;
import com.jjiang.bbmall.product.entity.CategoryEntity;
import com.jjiang.bbmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        // baseMapper就是CategoryDao
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2. 组装父子树型结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0; //说明是一级类别
        }).map((menu) -> {
            // 获得子分类
            menu.setChildren(getChildren(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        //2.2 找到父分类的子分类


        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前被删除的菜单，是否被别的地方引用了

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return (Long[]) paths.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有Category关联的数据
     *
     * @param category
     */
//    // 方法一
//    @Caching(evict = {
//            @CacheEvict(value = {"category"}, key = "'getLevelCategories'"),
//            @CacheEvict(value = {"category"}, key = "'getCatalogJson'"),
//    })
    // 方法二
    @CacheEvict(value = {"category"}, allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        // 1.先更新自己
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            // 2. 更新其他的
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }

    }

    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevelCategories() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    /**
     * 老版本的，未优化之前的函数
     *
     * @Override public Map<String, List<Catalog2Vo>> getCatalogJson() {
     * // 1.查出所有的1级分类
     * List<CategoryEntity> levelCategories = getLevelCategories();
     * // 2.封装数据
     * Map<String, List<Catalog2Vo>> collect = levelCategories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
     * // 1.根据每个一级分类得到2级分类数据
     * List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
     * // 2.封装数据
     * List<Catalog2Vo> catalog2Vos = null;
     * if (categoryEntities != null) {
     * catalog2Vos = categoryEntities.stream().map(l2 -> {
     * Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
     * // 找到3级的分类
     * List<CategoryEntity> categoryEntities1 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
     * <p>
     * List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
     * if (categoryEntities1 != null) {
     * catalog3Vos = categoryEntities1.stream().map(l3 -> {
     * return new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
     * }).collect(Collectors.toList());
     * }
     * catalog2Vo.setCatalog3List(catalog3Vos);
     * return catalog2Vo;
     * }).collect(Collectors.toList());
     * }
     * return catalog2Vos;
     * }));
     * return collect;
     * }
     **/

    // 新版本函数，优化之后
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDb() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 1.查出所有的1级分类
        List<CategoryEntity> levelCategories = getCategoryChildren(selectList, 0L);
        // 2.封装数据
        Map<String, List<Catalog2Vo>> collect = levelCategories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1.根据每个一级分类得到2级分类数据
            List<CategoryEntity> categoryEntities = getCategoryChildren(selectList, v.getCatId());
            // 2.封装数据
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找到3级的分类
                    List<CategoryEntity> categoryEntities1 = getCategoryChildren(selectList, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (categoryEntities1 != null) {
                        catalog3Vos = categoryEntities1.stream().map(l3 -> {
                            return new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return collect;
    }

    // 新版本函数，优化之后，且使用Redis分布式锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock(String key) {
        // 设置uuid
        String uuid = UUID.randomUUID().toString();

        // 抢占分布式锁, 并且设置锁过期时间
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(lock)) {
            Map<String, List<Catalog2Vo>> collect = null;
            try {
                // 加锁成功
                String catalogJSON = stringRedisTemplate.opsForValue().get(key);

                if (!StringUtils.isEmpty(catalogJSON)) {
                    // 缓存中有该数据
                    collect = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
                    });
                    return collect;
                }

                List<CategoryEntity> selectList = baseMapper.selectList(null);

                // 1.查出所有的1级分类
                List<CategoryEntity> levelCategories = getCategoryChildren(selectList, 0L);
                // 2.封装数据
                collect = levelCategories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    // 1.根据每个一级分类得到2级分类数据
                    List<CategoryEntity> categoryEntities = getCategoryChildren(selectList, v.getCatId());
                    // 2.封装数据
                    List<Catalog2Vo> catalog2Vos = null;
                    if (categoryEntities != null) {
                        catalog2Vos = categoryEntities.stream().map(l2 -> {
                            Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            // 找到3级的分类
                            List<CategoryEntity> categoryEntities1 = getCategoryChildren(selectList, l2.getCatId());
                            List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                            if (categoryEntities1 != null) {
                                catalog3Vos = categoryEntities1.stream().map(l3 -> {
                                    return new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                }).collect(Collectors.toList());
                            }
                            catalog2Vo.setCatalog3List(catalog3Vos);
                            return catalog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
                // 3.将从数据库查到的数据放入缓存。以JSON的格式进行存储
                stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(collect), 12 + new Random().nextInt(12), TimeUnit.HOURS);

            } finally {
                /*
                // 解锁【非原子操作！会有问题】
                String lockValue = stringRedisTemplate.opsForValue().get("lock");
                if(Objects.equals(lockValue, uuid)){
                    // 删除自己加的锁
                    stringRedisTemplate.delete("lock");
                }
                */
                // 原子操作解锁。lua脚本
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList("lock"), uuid);
            }
            return collect;
        } else {
            // 加锁失败，等待100ms之后重试[自旋]
            // 休眠一定时间
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock(key);
        }


    }

    // 新版本函数，优化之后，且使用Redisson分布式锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock(String key) {
        // 抢占分布式锁, 并且设置锁过期时间
        String lockName = "CatalogJson-lock";
        RLock lock = redissonClient.getLock(lockName);
        lock.lock();

        Map<String, List<Catalog2Vo>> collect;
        try {
            // 加锁成功
            String catalogJSON = stringRedisTemplate.opsForValue().get(key);

            if (!StringUtils.isEmpty(catalogJSON)) {
                // 缓存中有该数据
                collect = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
                });
                return collect;
            }

            List<CategoryEntity> selectList = baseMapper.selectList(null);

            // 1.查出所有的1级分类
            List<CategoryEntity> levelCategories = getCategoryChildren(selectList, 0L);
            // 2.封装数据
            collect = levelCategories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                // 1.根据每个一级分类得到2级分类数据
                List<CategoryEntity> categoryEntities = getCategoryChildren(selectList, v.getCatId());
                // 2.封装数据
                List<Catalog2Vo> catalog2Vos = null;
                if (categoryEntities != null) {
                    catalog2Vos = categoryEntities.stream().map(l2 -> {
                        Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        // 找到3级的分类
                        List<CategoryEntity> categoryEntities1 = getCategoryChildren(selectList, l2.getCatId());
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                        if (categoryEntities1 != null) {
                            catalog3Vos = categoryEntities1.stream().map(l3 -> {
                                return new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            }).collect(Collectors.toList());
                        }
                        catalog2Vo.setCatalog3List(catalog3Vos);
                        return catalog2Vo;
                    }).collect(Collectors.toList());
                }
                return catalog2Vos;
            }));
            // 3.将从数据库查到的数据放入缓存。以JSON的格式进行存储
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(collect), 12 + new Random().nextInt(12), TimeUnit.HOURS);

        } finally {
            lock.unlock();
        }
        return collect;
    }

    // 新版本函数，优化之后; 且加上redis缓存; 但是时自己实现的缓存
    public Map<String, List<Catalog2Vo>> getCatalogJsonImplByMySelf() {
        // 注意需要进行序列化和反序列化！
        String key = "catalogJSON";
        // 1.加入redis缓存
        String catalogJSON = stringRedisTemplate.opsForValue().get(key);
        Map<String, List<Catalog2Vo>> collect = null;
        if (StringUtils.isEmpty(catalogJSON)) {
            // 2.缓存中没有该数据
            collect = getCatalogJsonFromDbWithRedissonLock(key);
        } else {
            collect = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        return collect;
    }

    // 新版本函数，优化之后; 且加上redis缓存；使用SpringCache进行缓存
    @Override
    @Cacheable(value = {"category"}, key = "#root.method.name")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 1.查出所有的1级分类
        List<CategoryEntity> levelCategories = getCategoryChildren(selectList, 0L);
        // 2.封装数据
        Map<String, List<Catalog2Vo>> collect = levelCategories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1.根据每个一级分类得到2级分类数据
            List<CategoryEntity> categoryEntities = getCategoryChildren(selectList, v.getCatId());
            // 2.封装数据
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找到3级的分类
                    List<CategoryEntity> categoryEntities1 = getCategoryChildren(selectList, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (categoryEntities1 != null) {
                        catalog3Vos = categoryEntities1.stream().map(l3 -> {
                            return new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return collect;
    }

    private List<CategoryEntity> getCategoryChildren(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
    }

    /**
     * 递归查找父亲的类别
     *
     * @param catelogId 需要查询的id
     * @param paths     存储放置的路径的数组
     * @return 查询到的数组
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        // 1.搜集当前的节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找当前分类的所有子分类
     *
     * @param root 父类
     * @param all  所有类别
     * @return 带有子类的父类
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单[递归找法]
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}
